package org.douxiaoban.client.api;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class DBHttpClient{
	
	
	private static final int CONN_TIME_OUT = 20 * 1000;
	private static final int READ_TIME_OUT = 20 * 1000;
	
	private static final String CHARSET = "utf-8";
	
	public DBHttpClient(){
		
	}
	
	public String [] getData(String url, Map<String, String> params){
//		if(!isAvailable(mCtx)){
//			return null;
//		}
		HttpURLConnection conn = null;
		try {
//				 for test
//					   SocketAddress proxyAddress=new InetSocketAddress("192.168.3.140",8888);
//					   Proxy proxy=new Proxy(Proxy.Type.HTTP, proxyAddress);
//			url = makeUrl(url, params);
			String[] ret = new String[] { "505", "INIT_ERROR" };
			URL uri = new URL(url);
			conn = (HttpURLConnection) uri.openConnection();
			conn.setReadTimeout(CONN_TIME_OUT); 
			conn.setConnectTimeout(READ_TIME_OUT); 
			// 允许输入
			conn.setDoInput(true);
			// 允许输出
			conn.setDoOutput(true);
			// 不允许使用缓存
			conn.setUseCaches(false); 
			 //GET方法
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Connection", "close");
			conn.setRequestProperty("Charsert", CHARSET);
			InputStream in = null;
			// 得到响应码
			int res = conn.getResponseCode();
			ret[0] = String.valueOf(res);
			in = conn.getInputStream();
			int ch;
			StringBuilder sb2 = new StringBuilder();
			while ((ch = in.read()) != -1) {
					sb2.append((char) ch);
			}
			ret[1] = sb2.toString();
			conn.disconnect();
			return ret;
		}
		catch(Exception e){
			e.printStackTrace();
		} finally{
			if(conn != null){
				conn.disconnect();
			}
		}
		return null;
	}
}